import json
import re

from django import http
from django.views import View

from apps.areas.models import Address
from utils import constants
from utils.response_code import RETCODE


class AddressView(View):
    """新增地址"""

    def post(self, request):
        # 最多20个
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('name')
        mobile = json_dict.get('mobile')
        province = json_dict.get('provinces')
        city = json_dict.get('citys')
        district = json_dict.get('countys')
        place = json_dict.get('place')
        print(mobile)

        # 校验参数
        if not all([receiver,mobile,province,city,district,place]):
            return http.JsonResponse({'code':RETCODE.NECESSARYPARAMERR,'errmsg':'缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code':RETCODE.MOBILEERR,'errmsg':'手机号错误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                receiver = receiver,
                mobile = mobile,
                province = province,
                city = city,
                district=district,
                place=place
            )
        except Exception as e:
            print(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        # 返回给前端响应
        address_dict = {
            "id": address.id,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address': address_dict})
